package com.ccys.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.ccys.netty.config.NettyConfig;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author cloud fly
 * @description 客户端通道的处理器
 * @date 2024/2/28
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        NettyConfig.getUserChannelMapClient().put("666666",ctx.channel());
        NettyConfig.getUserChannelMapClient().put("bbb", ctx.channel());
        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("channelId",ctx.channel().id().asLongText());
        jsonObject.put("state","success");
        jsonObject.put("userId", "666666");
        jsonObject.toJSONString()*/
        String data = "GET /GetHttp?booking_id=12132&member_id=23a53876-5aed-4b3d-b5dd-36934aac124d HTTP/1.1\n" +
            "Host: 192.168.2.120:1024\n" +
            "Connection: Upgrade\n" +
            "Upgrade: websocket\n" +
            "Sec-WebSocket-Version: 13\n" +
            "Sec-WebSocket-Key: ffDqssUVaqpr3PrEMeadDQ==";
        //发送消息到服务端
        ctx.writeAndFlush(Unpooled.copiedBuffer(data, CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收服务端发送过来的消息
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("自定义客户端收到服务端" + ctx.channel().remoteAddress() + "的消息：" + byteBuf.toString(CharsetUtil.UTF_8));
        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("channelId",ctx.channel().id().asLongText());
        jsonObject.put("state","success");
        jsonObject.put("userId", "666666");*/
        String data = "GET /GetHttp?booking_id=12132&member_id=23a53876-5aed-4b3d-b5dd-36934aac124d HTTP/1.1\n" +
            "Host: 192.168.2.120:1024\n" +
            "Connection: Upgrade\n" +
            "Upgrade: websocket\n" +
            "Sec-WebSocket-Version: 13\n" +
            "Sec-WebSocket-Key: ffDqssUVaqpr3PrEMeadDQ==";
        ctx.channel().writeAndFlush("收到服务端连接时消息：发送连接身份信息给服务端" + data);

    }

}
